package com.ljpz.userinfo.service;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.abel533.entity.Example;
import com.ljpz.userinfo.bean.LjpzResult;
import com.ljpz.userinfo.mapper.UserinfoMapper;
import com.ljpz.userinfo.pojo.Userinfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

/**
 * Created by liujunchen on 2017/2/9.
 */
@Service
public class UserinfoService {
    @Autowired
    private UserinfoMapper userinfoMapper;
    private  static  final ObjectMapper   MAPPER = new ObjectMapper()  ;

    /**
     * 保存用户资料信息
     *
     * @param json
     * @return
     */
    public LjpzResult createUserinfo(String json) {
        Userinfo userinfo  = null ;
        try {
            userinfo =  MAPPER.readValue(json,Userinfo.class);
            if ( userinfo   !=null){
                //保存对象
                this.userinfoMapper.insert(userinfo)   ;
                return LjpzResult.ok(userinfo.getNickname())  ;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return  LjpzResult.build(400,"error");
    }
    public  Userinfo   queryByNickname(Long  userId  ){
        Userinfo userinfo  = new Userinfo();
        userinfo.setUserId(userId);
        return  userinfoMapper.selectOne(userinfo) ;
    }

    public LjpzResult updateUserinfo(String json) {
        Userinfo  userinfo  = null ;

        try {
            userinfo=MAPPER.readValue(json,Userinfo.class)  ;
            if (userinfo !=null){
                Long   userId  = userinfo.getUserId();
                Example example = new Example(Userinfo.class) ;
                example.createCriteria().andEqualTo("userId", userId);
                this.userinfoMapper.updateByExampleSelective(userinfo,example)  ;
                return  LjpzResult.ok(userinfo.getNickname());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return LjpzResult.build(400,"error");
    }
}
